package com.sxfq.loansupermarket.backsystem.modular.base;


import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ApprovalProcessInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import static com.sxfq.loansupermarket.backsystem.modular.arrival.controller.MsgSendController.querySendDetails;
import static com.sxfq.loansupermarket.backsystem.modular.arrival.controller.MsgSendController.sendSms;

@Component
@Configuration
@EnableScheduling
public class SaticScheduleTask {
    @Autowired
    private SqlMapper sqlMapper;
    /**
     * 定时任务发送短信
     */
//    @Scheduled(cron = "0 0 10 * * ?")
//    public  void   msgSendAotu() throws ClientException, InterruptedException {
//        //恩施区域查询门店
//        String nameSql = "select id, simplename, fullname,area_abbreviation,abbreviation from dept where tips=1 and (area_abbreviation='yiya_essj_' or area_abbreviation='yiya_esxj_') order by num desc;";
//        List<Dept> dimensionList = sqlMapper.selectList(nameSql, Dept.class);
//        String times = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        String time = times.substring(5,10);
//        for (Dept info : dimensionList) {
//            String table = info.getAbbreviation() + "customer_info";
//            String selectSql = "select id,birthday,arrival_store as arrivalStore,customer_name as customerName,customer_phone as customerPhone from " + table + " where birthday like'%-" + time + "' group by customerPhone ; ";
//            List<CustomerInfo> birInfoList = sqlMapper.selectList(selectSql, CustomerInfo.class);
//            String phoneNumbers ="";
//            String customerName ="";
//            String outpatientName="";
//            String templateCode = "SMS_151575670";
//            String signName = "钛植口腔" + info.getSimplename();
//            if(birInfoList.size()>0){
//                for (CustomerInfo infos : birInfoList) {
//                    phoneNumbers = infos.getCustomerPhone();
//                    customerName = infos.getCustomerName();
//                    outpatientName = info.getSimplename();
//                    try {
//                        if(phoneNumbers != null){
//                            phoneNumbers = phoneNumbers.substring(0, 11);
//                        }else{
//                            continue;
//                        }
//                        if(customerName == null){
//                            customerName ="客户";
//                        }else{
//                            customerName = infos.getCustomerName();
//                        }
//                    } catch (StringIndexOutOfBoundsException e) {
//                        continue;
//                    }
//                    String messageContent = "尊敬的"+infos.getCustomerName()+"，在这个属于你的精彩日子里,祝你生日快乐,工作顺利!愿你好上加好,福中更福! 钛植口腔"+outpatientName+"。";
//                    SendSmsRequest request = new SendSmsRequest();
//                    request.setPhoneNumbers(phoneNumbers);
//                    request.setSignName(signName);
//                    request.setTemplateCode(templateCode);
//                    request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"customerName\":\"" + customerName + "\"} ");
//                    request.setOutId("123");
//                    SendSmsResponse response = sendSms(request);
//                    System.out.println("短信接口返回的数据----------------");
//                    System.out.println("Code=" + response.getCode());
//                    System.out.println("Message=" + response.getMessage());
//                    System.out.println("RequestId=" + response.getRequestId());
//                    System.out.println("BizId=" + response.getBizId());
//                    Thread.sleep(300L);
//                    //查明细
//                    if (response.getCode() != null && response.getCode().equals("OK")) {
//                        QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
//                        System.out.println("短信明细查询接口返回数据----------------");
//                        System.out.println("Code=" + querySendDetailsResponse.getCode());
//                        System.out.println("Message=" + querySendDetailsResponse.getMessage());
//                        System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
//                        System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
//                        String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`, `outpatient_name`, `is_success`) VALUES" +
//                                "('系统', '" + infos.getCustomerName() + "', '" + infos.getCustomerPhone() + "', '" + messageContent + "','" + infos.getArrivalStore() + "',1);";
//                        sqlMapper.insert(insertsql);
//                    } else {
//                        String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`,`outpatient_name`, `is_success`) VALUES" +
//                                "('系统', '" + infos.getCustomerName() + "', '" + infos.getCustomerPhone() + "', '" + messageContent + "','" + infos.getArrivalStore() + "',2);";
//                         sqlMapper.insert(insertsql);
//                    }
//                }
//            }else{
//                continue;
//            }
//        }
//    }

    /**
     * 二次开发 保护期满一年之后渠道自动变为直接上门  定时任务
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateChanelAotu() throws Exception{
        //查询一级渠道为二次开发的
        String selSql = "select id,one_channel from reservations_info where one_channel='二次开发'";
        List<ApprovalProcessInfo> infoList = sqlMapper.selectList(selSql,ApprovalProcessInfo.class);
        if(infoList.size()>0){
            for(int i=0;i<infoList.size();i++){
                //通过预约ID 查询到过哪些店有消费
                String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + infoList.get(i).getId() + "' ";
                List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
                String rechargeTables = "";
                if(abbreviationList.size()>0){
                    for (int j = 0; j < abbreviationList.size(); j++) {
                        String head = abbreviationList.get(j);
                        if (j == abbreviationList.size() - 1) {
                            rechargeTables += "select a.id,a.operation_time,a.recharge_time,a.reservations_id,t2.time as time from " + head + "recharge_info a LEFT JOIN reservations_second_development t2  " +
                                    "on a.reservations_id = t2.reservations_id where DATEDIFF(a.recharge_time,t2.time)>0 and a.reservations_id='" + infoList.get(i).getId() + "' ";
                        } else {
                            rechargeTables += "select a.id,a.operation_time,a.recharge_time,a.reservations_id,t2.time as time from " + head + "recharge_info a LEFT JOIN reservations_second_development t2 " +
                                    "on a.reservations_id = t2.reservations_id where DATEDIFF(a.recharge_time,t2.time)>0 and a.reservations_id='" + infoList.get(i).getId() + "' union ";
                        }
                    }
                }
                String custimeSql = "select t1.id as id,t1.reservations_id as reservationsId, t1.recharge_time as rechargeTime,left(t1.operation_time,19) as operationTime, t1.time " +
                        "from (" + rechargeTables + ") t1 where  t1.reservations_id = '" + infoList.get(i).getId() + "' group by t1.recharge_time order by t1.recharge_time asc limit 1";
                RechargeInfo info = sqlMapper.selectOne(custimeSql,RechargeInfo.class);
                if(info!=null){
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    //第一次结账时间
                    LocalDateTime firstDateTime = LocalDateTime.parse(info.getRechargeTime(), df);
                    Long milliLastTime = firstDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //保护期一年的时间戳
                    Long thTime = 31536000000L;
                    Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    //如果满一年 就将渠道变为直接上门
                    if((milliSecond.longValue()-milliLastTime.longValue())>thTime.longValue()){
                       String updateSql = "update reservations_info a set a.one_channel='直接上门',a.two_channel='直接上门',a.thr_channel='直接上门',a.one_medium='直接上门',a.two_medium='直接上门',a.thr_medium='直接上门' where id='"+infoList.get(i).getId()+"'";
                       sqlMapper.update(updateSql);
                        String updateSqlsc = "update reservations_infosc a set a.one_channel='直接上门',a.two_channel='直接上门',a.thr_channel='直接上门',a.one_medium='直接上门',a.two_medium='直接上门',a.thr_medium='直接上门' where id='"+infoList.get(i).getId()+"'";
                        sqlMapper.update(updateSqlsc);
                    }
                }
            }
        }
    }
}
